'''
Created on Jun 6, 2012

@author: thomas_dao
'''

from google.appengine.ext import ndb
from entity.entity import Event, RSVP
from datetime import datetime, timedelta
from operator import attrgetter

@ndb.tasklet
def get_by_organizer(organizer_key, **q_options):
    qry = Event.query(Event.organizer == organizer_key).order(-Event.created_time)
    data = yield qry.fetch_async(20, **q_options)
    raise ndb.Return(data)

@ndb.tasklet
def get_rsvps(event_key, status=None, **q_options):
    qry = RSVP.query(RSVP.event == event_key)
    if status is not None:
        qry = qry.filter(RSVP.status == status)
    
    qry = qry.order(-RSVP.created_time)
    
    data = yield qry.fetch_async(20, **q_options)
    raise ndb.Return(data)              

@ndb.tasklet
def get_all(**q_options):
    qry = Event.query().order(-Event.popularity).order(-Event.created_time)
    events, next_curs, more = yield qry.fetch_page_async(20, **q_options)
    raise ndb.Return(events, next_curs, more)

@ndb.tasklet
def get_by_category(category_key, **q_options):
    qry = Event.query(Event.category == category_key).order(-Event.popularity).order(-Event.created_time)
    events, next_curs, more = yield qry.fetch_page_async(20, **q_options)
    raise ndb.Return(events, next_curs, more)


@ndb.tasklet
def get_future_events(**q_options):
    # Current event: start_time < current_time < end_time
    current_time = datetime.now()
    qry = Event.query(Event.start_time >= current_time)
    events = yield qry.fetch_async(**q_options)
    events = sorted(events, key=attrgetter('created_time'), reverse=True)
    raise ndb.Return(events)

@ndb.tasklet
def get_current_events(**q_options):
    # Current event: start_time < current_time < end_time
    current_time = datetime.now()
    qry = Event.query(Event.end_time >= current_time)
    events = yield qry.fetch_async(**q_options)
    events = sorted(events, key=attrgetter('created_time'), reverse=True)
    raise ndb.Return(events)

@ndb.tasklet
def get_past_events(duration, **q_options):
    """
    @param duration: time from current date back when we want to retrieve events 
    """
    # Past event: end_time < current_time
    # and end_time > current_time - duration
    current_time = datetime.now()
    qry = Event.query(Event.end_time < current_time, Event.end_time > current_time-duration)
    events = yield qry.fetch_async(**q_options)
    events = sorted(events, key=attrgetter('created_time'), reverse=True)
    
    raise ndb.Return(events)

@ndb.tasklet
def get_past_month_events(**q_options):
    duration = timedelta(weeks=4)
    events = yield get_past_events(duration, **q_options)
    raise ndb.Return(events)


